package demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(2000);
        System.out.println("服务器启动！");
        while (true) {
            //1、把内核中已经建立好的连接拿到应用程序中-客户端上线
            Socket clientSocket = serverSocket.accept();
            System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress(), clientSocket.getPort());

            //2、进行数据交互
            try(InputStream in= clientSocket.getInputStream(); OutputStream out= clientSocket.getOutputStream()){
                //(1)客户端可能发来多条数据--循环处理
                while (true){
                    //(2)读取请求直到完毕客户端下线
                    Scanner scanner=new Scanner(in);
                    if (!scanner.hasNext()){
                        System.out.printf("[%s:%d] 客户端下线",clientSocket.getInetAddress(),clientSocket.getPort());
                        break;
                    }
                    //(3)解析请求
                    String request=scanner.next();
                    //(4)响应
                    String response=process(request);
                    //(5)返回响应给客户端
                    //out.write(response.getBytes());
                    PrintWriter pw=new PrintWriter(out);
                    pw.print(response);
                    pw.flush();
                    //(6)打印此次请求交互过程得内容
                    System.out.printf("[%s:%d] req=%s resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
                }
            }
        }
    }
    private static String process(String request) {
        return request;
    }
}

